#!/usr/bin/python
import sqlite3
import os
import cgi
import cgitb
from Cookie import SimpleCookie
from pygallib import userlib
from pygallib import usersession
from pygallib import layoutlib
from pygallib import albumlib
from pygallib import picturelib

cgitb.enable()

logged_in = usersession.logged_in()
fields = cgi.FieldStorage()

if "id" in fields:
  album_id = int(fields["id"].value)
  # Get album information
  album = albumlib.get_album(album_id)
  # Get user who created album
  user = userlib.get_user_by_id(album["user_id"])
  user_authorized = False
  if logged_in:
    session_user = usersession.get_session_user()
    if (session_user["user_id"] == user["user_id"] or
        session_user["root"] == 1):
      user_authorized = True
  
  # look for reactivate
  if user_authorized:
    if "cmd" in fields:
      if "reactivate" == fields["cmd"].value:
        picturelib.reactivate_picture(album_id, user["username"], 
            fields["picid"].value)

  # Read all pictures in album
  (picture_cur, conn) = albumlib.get_deleted_pictures(album_id)

headers = {}
headers["Content-type"] = "text/html"
layoutlib.print_http_headers(headers)
layoutlib.print_page_open("PyGallery - Recycle Bin")
print("<body>")
menu = []
menu.append(("Home", "gallery.cgi"))
layoutlib.print_page_header(menu, session_user)

print('<div id="page_body">')
if not user_authorized:
  print('<p>Click <a href="gallery.cgi">here</a> for the gallery.</p>')
elif "id" not in fields:
  print('<p>No album selected. Pick one <a href="gallery.cgi">here</a>.</p>')
else:
  # Print header
  print('<h1>%s <span>by %s</span></h1>' % (album["name"], user["username"]))
  print('<h2>Recycle Bin</h2>')
  # Print album command list
  print('<p><a href="album.cgi?id=%d">Go back to album</a></li>'
      % (album_id))
  # Display images
  print('<ul id="album_container">')
  for picture in picture_cur:
    image_url = '/PictureShare/users/%s/%s/%s' % \
        (user["username"], "album"+str(album_id), picture["file_name"])
    image_thumb_url = '/PictureShare/users/%s/%s/%s' % \
        (user["username"], "albumthumb"+str(album_id), picture["file_name"])
    print('<li>')
    print('<a href="%s"><img height="100" src="%s" /></a>' % \
        (image_url, image_thumb_url))
    print('%s<br>' % picture["label"])
    print("""
    <a href="album_recyclebin.cgi?id=%d&cmd=reactivate&picid=%d">Restore</a>
    """ % (album_id, picture["picture_id"]))
    print('</li>')
  print('</ul>')
  picture_cur.close()
print('</div>')
conn.close()
layoutlib.print_page_close()
